package io.github.handyang.algorithms.sort;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * 只能用作数字排序
 */
public class BucketSortAlgorithms implements SortAlgorithms {

    @Override
    public void sort(int[] arr) {
        int min = arr[0], max = min;
        for (int item : arr) {
            if (item > max) max = item;
            if (item < min) min = item;
        }

        int bucketNum = max / 10 - min / 10 + 1;
        ArrayList[] buckets = new ArrayList[bucketNum];

        for (int item : arr) {
            int bucketIndex = bucketIndex(item, min, 10);
            if (buckets[bucketIndex] == null) buckets[bucketIndex] = new ArrayList();

            buckets[bucketIndex].add(item);
        }

        int i = 0;
        for (ArrayList<Integer> bucket : buckets) {
            if (bucket == null) continue;

            bucket.sort(Comparator.comparingInt(o -> o));
            for (Integer item : bucket) {
                arr[i++] = item;
            }
        }
    }

    private int bucketIndex(int num, int min, int step) {
        return (num - min + 1) / step;
    }
}
